package com.person.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传和下载
 */
@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String basePath;
    /**
     * 文件上传
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {

        log.info("文件上传{}",file.toString());
        //获取文件名
        String originalFilename = file.getOriginalFilename();
        //随机生成文件名
        String fileName= UUID.randomUUID().toString()+
                originalFilename
                        .substring(originalFilename.lastIndexOf("."));
        log.info("文件名{}",fileName);

        //判断文件夹是否存在
        File dir = new File(basePath);
        //不存在创建
        if (!dir.exists()){
            dir.mkdirs();
        }
        file.transferTo(new File(basePath+fileName));
        return R.success(fileName);
    }

    /**
     * 文件下载
     */
    @GetMapping("/download")
    public void download(HttpServletResponse response, String name) throws IOException {
        //输入流，获取文件内容
        FileInputStream fileInputStream =new FileInputStream(new File(basePath+name));
        //输出流，写入文件内容，写回浏览器
        ServletOutputStream outputStream = response.getOutputStream();

        //设置响应回去的类型,"image/jpeg" 固定类型
        response.setContentType("image/jpeg");
        byte[] bytes = new byte[1024];
        int len=0;
        while ((len=fileInputStream.read(bytes))!=-1){
            outputStream.write(bytes,0,len);
            outputStream.flush();
        }
        outputStream.close();
        fileInputStream.close();
    }
}
